package com.easy.work.function.mall.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.base.syslib.Logs;
import com.base.syslib.pulltorefresh.PullToRefreshBase;
import com.base.syslib.pulltorefresh.PullToRefreshListView;
import com.base.syslib.util.MessageTools;
import com.easy.work.R;
import com.easy.work.app.AppSession;
import com.easy.work.app.BaseActivity;
import com.easy.work.bean.MallGoodsBean;
import com.easy.work.function.mall.adapter.CommitOrderAdapter;
import com.easy.work.function.mall.bean.AddressBean;
import com.easy.work.function.mall.bean.NeedIntegralEvent;
import com.easy.work.function.mall.bean.SelectAddressEvent;
import com.easy.work.http.BaseResponse;
import com.easy.work.http.HttpClient;
import com.easy.work.http.request.AllAddressRequest;
import com.easy.work.http.request.MallExchangeRequest;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author zhangfeng
 * @date 2017/12/20
 * @desc 提交订单
 */

public class CommitOrderActivity extends BaseActivity implements PullToRefreshBase.OnRefreshListener<ListView> {

    private static final String TAG = CommitOrderActivity.class.getSimpleName();
    private static final String GOODS_INFO = "MallGoodsBean";

    @BindView(R.id.tv_integral)
    TextView mTvTotalIntegral;
    @BindView(R.id.listView)
    PullToRefreshListView refreshListView;
    private ListView listView;
    private CommitOrderAdapter mAdapter;

    private MallGoodsBean bean;

    private EditText mEtMsg;
    private TextView mTvIntegral;

    private TextView mTvReciveName;
    private TextView mTvPhone;
    private TextView mTvAddress;

    private String addressId = "";

    public static void start(Context ctx, MallGoodsBean bean) {
        Intent intent = new Intent(ctx, CommitOrderActivity.class);
        intent.putExtra(GOODS_INFO, bean);
        ctx.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_commit_record);
        ButterKnife.bind(this);
        initTitle("提交订单");

        EventBus.getDefault().register(this);

        bean = (MallGoodsBean) getIntent().getSerializableExtra(GOODS_INFO);
        initListView();

        AppSession.setPullFormartRefreshTime(refreshListView);
        refreshListView.doPullRefreshing(true, 0);
    }

    /**
     * ListView初始化
     */
    private void initListView() {
        refreshListView.setPullLoadEnabled(true);
        refreshListView.setPullRefreshEnabled(true);
        refreshListView.setOnRefreshListener(this);

        listView = refreshListView.getRefreshableView();
        listView.setDivider(null);

        addHeadView();
        addFooterView();

        List<MallGoodsBean> list = new ArrayList<>();
        list.add(bean);
        mAdapter = new CommitOrderAdapter(this, 1, list);
        listView.setAdapter(mAdapter);

        getAllAddressList();
    }

    /**
     * 添加头部
     */
    private void addHeadView() {
        View headView = getLayoutInflater().inflate(R.layout.head_order_address, listView, false);
        RelativeLayout lySelect = (RelativeLayout) headView.findViewById(R.id.ly_select_address);
        mTvReciveName = (TextView) headView.findViewById(R.id.tv_receive_name);
        mTvPhone = (TextView) headView.findViewById(R.id.tv_phone);
        mTvAddress = (TextView) headView.findViewById(R.id.tv_address);

        lySelect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SelectAddressActivity.start(oThis);
            }
        });

        listView.addHeaderView(headView);
    }

    /**
     * 添加尾部
     */
    private void addFooterView() {
        View footerView = getLayoutInflater().inflate(R.layout.footer_order_message, listView, false);
        mEtMsg = (EditText) footerView.findViewById(R.id.et_msg);
        mTvIntegral = (TextView) footerView.findViewById(R.id.tv_total_price);

        String text = bean.integral + "积分";
        mTvIntegral.setText(text);
        mTvTotalIntegral.setText(text);

        listView.addFooterView(footerView);
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        refreshListView.onPullUpRefreshComplete();
        refreshListView.onPullDownRefreshComplete();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
        refreshListView.onPullUpRefreshComplete();
        refreshListView.onPullDownRefreshComplete();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onNeedIntegralEvent(NeedIntegralEvent event) {
        String text = event.totalIntegral + "积分";
        mTvIntegral.setText(text);
        mTvTotalIntegral.setText(text);
    }

    private void setReceiveMsg(AddressBean.ListEntity entity) {
        addressId = entity.consigneeId;
        mTvReciveName.setText("收货人：" + entity.name);
        mTvPhone.setText(entity.phone);
        mTvAddress.setText("收货地址：" + entity.provinceText + entity.cityText + entity.areaText + entity.address);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSelectAddressEvent(SelectAddressEvent event) {
        setReceiveMsg(event.entity);
    }

    private void getAllAddressList() {
        showDialog();
        final AllAddressRequest request = new AllAddressRequest();
        request.userId = AppSession.getInstance().getUserId();
        Logs.e(TAG, "userId:" + request.userId);
        HttpClient.post(request, new HttpClient.onSuccessListener() {
            @Override
            public void onSuccess(BaseResponse response) {
                closeDialog();
                AddressBean bean = (AddressBean) response;
                if (bean != null && bean.list != null && !bean.list.isEmpty()) {
                    setReceiveMsg(bean.list.get(0));
                }
            }
        }, new HttpClient.onFailListener() {
            @Override
            public void onFail(int code, String msg) {
                closeDialog();
            }
        });
    }

    @OnClick(R.id.tv_submit_order)
    public void submit() {
        if (TextUtils.isEmpty(mTvPhone.getText().toString())) {
            MessageTools.showToast(oThis, "请选择收货地址");
            return;
        }
        mallExchange();
    }

    /**
     * 兑换商品
     */
    private void mallExchange() {
        MallExchangeRequest request = new MallExchangeRequest();
        request.goodsId = bean.goodsId;
        request.consigneeId = addressId;
        request.userId = AppSession.getInstance().getUserId();
        request.remind = TextUtils.isEmpty(mEtMsg.getText().toString()) ? "" : mEtMsg.getText().toString();
        request.number = mAdapter.getNumber();
        Logs.e(TAG, "goodsId:" + bean.goodsId);
        Logs.e(TAG, "addressId:" + addressId);
        Logs.e(TAG, "number:" + mAdapter.getNumber());
        Logs.e(TAG, "remind:" + request.remind);
        HttpClient.post(request, new HttpClient.onSuccessListener() {
            @Override
            public void onSuccess(BaseResponse response) {
                MessageTools.showToast(oThis, "兑换成功");
                finish();

            }
        }, new HttpClient.onFailListener() {
            @Override
            public void onFail(int code, String msg) {
                MessageTools.showToast(oThis, msg);
                Logs.e(tag, msg);
            }
        });
    }
}
